﻿<?php
/**
 * ECSHOP微信新版JSAPI支付插件
 */


class wx_qrcode
{

	function __construct()
	{
		$payment = array(
            'appid'=>'wxb83f4f364d253638',
            'mchid'=>'1279736701',
            'key'=>'062f1bed589c39394ee3643809222211'
        );
    
        if(!defined('WXAPPID'))
        {
            $root_url = $GLOBALS['web_url'];
            define("WXAPPID", $payment['appid']);
            define("WXMCHID", $payment['mchid']);
            define("WXKEY", $payment['key']);
            define("WXAPPSECRET", $payment['appsecret']);
            define("WXCURL_TIMEOUT", 30);
            define('WXNOTIFY_URL',$root_url.'wx_native_callback.php');
            define('WXSSLCERT_PATH',dirname(__FILE__).'/WxPayPubHelper/cacert/apiclient_cert.pem');
            define('WXSSLKEY_PATH',dirname(__FILE__).'/WxPayPubHelper/cacert/apiclient_key.pem');
            
            define('WXJS_API_CALL_URL',$root_url.'wx_refresh.php');
        }
        require_once(dirname(__FILE__)."/WxPayPubHelper/WxPayPubHelper.php");

	}
    function pay($order_id,$amount){
        $order=array('order_sn'=>$order_id,'log_id'=>1,'order_amount'=>$amount);
        echo $this->get_code($order);
    }
	function get_code($order)
	{
		

		if($order["wx_pay_image"]){
			$html = '<div class="wx_qrcode" style="text-align:center">';
            $html .= "<img src='".BASEURL.$order["wx_pay_image"]."'/>";
            $html .= "</div>";

            $html.="<div class=\"right\"><span class=\"t1\">微信扫一扫上面二维码,进行支付.</span>
<span class='t2'><a href=\"user.php?act=order_list\">支付成功后点击此处查看我的订单</a></span></div>";
		}else{
			$unifiedOrder = new UnifiedOrder_pub();
	
			$unifiedOrder->setParameter("body",$order['order_sn']);//商品描述
			$out_trade_no = $order['order_sn'];
			$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号 
			$unifiedOrder->setParameter("attach",strval($order['log_id']));//商户支付日志
			$unifiedOrder->setParameter("total_fee",strval(intval($order['order_amount']*100)));//总金额
			$unifiedOrder->setParameter("notify_url",WXNOTIFY_URL);//通知地址 
			$unifiedOrder->setParameter("trade_type","NATIVE");//交易类型
			$unifiedOrderResult = $unifiedOrder->getResult();
	var_dump($unifiedOrderResult);
			$html = '<button type="button" onclick="javascript:alert(\'出错了\')">微信支付</button>';
			if($unifiedOrderResult["code_url"] != NULL)
			{
				$code_url = $unifiedOrderResult["code_url"];
				$html = '<div class="wx_qrcode" style="text-align:center">';
				$html .= $code_url;//$this->getcode($code_url,$order["order_id"]);
				$html .= "</div>";
                $html.="<div class=\"right\"><span class=\"t1\">微信扫一扫上面二维码,进行支付.</span>
<span class='t2'><a href=\"user.php?act=order_list\">支付成功后点击此处查看我的订单</a></span></div>";
			}
		}
        

        return $html;
	}
    function respond()
    {
        $payment  = get_payment('wx_new_qrcode');

        $notify = new Notify_pub();
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        
        if($payment['logs'])
        {
            $this->log(ROOT_PATH.'/data/wx_new_log.txt',"传递过来的XML\r\n".var_export($xml,true));
        }
        $notify->saveData($xml);
        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                if($payment['logs']){
                    $this->log(ROOT_PATH.'/data/wx_new_log.txt',"return_code失败\r\n");
                }
            }
            elseif($notify->data["result_code"] == "FAIL"){
                //此处应该更新一下订单状态，商户自行增删操作
                if($payment['logs']){
                    $this->log(ROOT_PATH.'/data/wx_new_log.txt',"result_code失败\r\n");
                }
            }
            else{
                //此处应该更新一下订单状态，商户自行增删操作
                if($payment['logs']){
                    $this->log(ROOT_PATH.'/data/wx_new_log.txt',"支付成功\r\n");
                }
                $total_fee = $notify->data["total_fee"];
                $log_id = $notify->data["attach"];
                $sql = 'SELECT order_amount FROM ' . $GLOBALS['ecs']->table('pay_log') ." WHERE log_id = '$log_id'";
                $amount = $GLOBALS['db']->getOne($sql);
                
                if($payment['logs'])
                {
                    $this->log(ROOT_PATH.'/data/wx_new_log.txt','订单金额'.$amount."\r\n");
                }
                
                if(intval($amount*100) != $total_fee)
                {
                    
                    if($payment['logs'])
                    {   
                        $this->log(ROOT_PATH.'/data/wx_new_log.txt','订单金额不符'."\r\n");
                    }
                    
                    echo 'fail';
                    return;
                }

                order_paid($log_id, 2);
                return true;
            }

        }
        else
        {
            $this->log(ROOT_PATH.'/data/wx_new_log.txt',"签名失败\r\n");
        }
        return false;
    }


    function getcode($url,$order_id){
		global $db,$ecs;
        /*if(file_exists(ROOT_PATH . 'includes/phpqrcode.php')){
            include_once(ROOT_PATH . 'includes/phpqrcode.php');
        }
        // 纠错级别：L、M、Q、H 
        $errorCorrectionLevel = 'Q';  
        // 点的大小：1到10 
        $matrixPointSize = 5;
        // 生成的文件名
        $tmp = ROOT_PATH .'images/qrcode/';
        if(!is_dir($tmp)){
            @mkdir($tmp);
        }
        $filename = $tmp . $errorCorrectionLevel . $matrixPointSize.rand(1000,9999). '.png';
        QRcode::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 2);*/
		include_once(ROOT_PATH."include/common.function.php");
		$filename = get_erweima($url);
		$db->query("update ".$ecs->table("order_info")." set wx_pay_image='".$filename."' where order_id='".$order_id."'");
        return '<img src="/'. $filename.'" />';
    }
    
    function log($file,$txt)
    {
       $fp =  fopen($file,'ab+');
       fwrite($fp,'-----------'.local_date('Y-m-d H:i:s').'-----------------');
       fwrite($fp,$txt);
       fwrite($fp,"\r\n\r\n\r\n");
       fclose($fp);
    }
    
}
